const cloud = require('wx-server-sdk');

cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const {
    partName,
    customerName,
    orderNumber,
    manufacturerNam,
    partImage,
    material,
    postprocessing,
    quantity,
    blankingImg,
    blankingTime,
    processingImage,
    processingTime,
    handleImage,
    handleTime,
    qualityImg,
    qualityTime,
    deliveryTime,
    remarks,
    afterSale,
    sendImage,
  } = event;

  try {
    // 查询当前订单是否存在
    const orderRes = await db.collection('Order').where({
      orderNumber: orderNumber
    }).get();

    if (orderRes.data.length > 0) {
      // 如果订单存在，查看订单中的厂家字段是否包含前端传入的厂家名
      const existingManufactors = orderRes.data[0].manufactor || [];

      if (!existingManufactors.includes(manufacturerNam)) {
        // 如果厂家名不存在订单的厂家字段中，添加厂家名到订单的厂家数组中
        existingManufactors.push(manufacturerNam);

        // 更新订单的厂家字段
        await db.collection('Order').doc(orderRes.data[0]._id).update({
          data: {
            manufactor: existingManufactors
          }
        });
      }
    } else {
      // 如果订单不存在，可以根据实际情况返回错误信息或进行其他处理
      return {
        success: false,
        errorMessage: '订单不存在'
      };
    }

    // 添加零件信息到 Parts 集合
    const currentTime = new Date();
    const result = await db.collection('Parts').add({
      data: {
        partName: partName,
        customerName: customerName,
        orderNumber: orderNumber,
        manufacturerNam: manufacturerNam,
        partImage: partImage,
        quantity: quantity,
        blankingImg: blankingImg,
        blankingTime: blankingTime,
        processingImage: processingImage,
        processingTime: processingTime,
        handleImage: handleImage,
        handleTime: handleTime,
        qualityImg: qualityImg,
        qualityTime: qualityTime,
        deliveryTime: deliveryTime,
        remarks: remarks,
        afterSale: afterSale,
        createdAt: currentTime,
        updatedAt: currentTime,
        material: material,
        postprocessing: postprocessing,
        sendImage: sendImage
      }
    });

    return {
      success: true,
      partId: result._id
    };
  } catch (err) {
    console.error('Error adding part information:', err);
    return {
      success: false,
      errorMessage: err
    };
  }
};
